import { defineStore } from 'pinia'
import type { TabItem, BreadcrumbItem, SystemConfig } from '@/types/system'

interface AppState {
  // 系统配置
  config: SystemConfig
  
  // 侧边栏状态
  sidebarCollapsed: boolean
  sidebarWithoutAnimation: boolean
  
  // 设备类型
  device: 'desktop' | 'tablet' | 'mobile'
  
  // 主题配置
  theme: 'light' | 'dark' | 'auto'
  primaryColor: string
  
  // 布局配置
  layout: 'vertical' | 'horizontal' | 'mix'
  fixedHeader: boolean
  fixedSidebar: boolean
  showBreadcrumb: boolean
  showTabs: boolean
  showFooter: boolean
  
  // 标签页
  tabs: TabItem[]
  cachedViews: string[]
  
  // 面包屑
  breadcrumbs: BreadcrumbItem[]
  
  // 加载状态
  loading: boolean
  
  // 全屏状态
  fullscreen: boolean
  
  // 语言
  language: string
  
  // 页面尺寸
  size: 'default' | 'large' | 'small'
}

export const useAppStore = defineStore('app', {
  state: (): AppState => ({
    config: {
      title: import.meta.env.VITE_APP_TITLE || 'Kexio权限管理系统',
      version: import.meta.env.VITE_APP_VERSION || '1.0.0',
      tenantEnabled: import.meta.env.VITE_TENANT_ENABLED === 'true',
      apiBaseUrl: import.meta.env.VITE_API_BASE_URL || '/api',
      apiTimeout: parseInt(import.meta.env.VITE_API_TIMEOUT) || 30000,
      uploadSizeLimit: parseInt(import.meta.env.VITE_UPLOAD_SIZE_LIMIT) || 10485760,
      cacheEnabled: import.meta.env.VITE_CACHE_ENABLED === 'true',
      cacheExpire: parseInt(import.meta.env.VITE_CACHE_EXPIRE) || 7200000
    },
    
    sidebarCollapsed: false,
    sidebarWithoutAnimation: false,
    
    device: 'desktop',
    
    theme: 'light',
    primaryColor: '#409EFF',
    
    layout: 'vertical',
    fixedHeader: true,
    fixedSidebar: true,
    showBreadcrumb: true,
    showTabs: false,  // 关闭标签页显示
    showFooter: true,
    
    tabs: [],
    cachedViews: [],
    
    breadcrumbs: [],
    
    loading: false,
    fullscreen: false,
    
    language: 'zh-CN',
    size: 'default'
  }),

  getters: {
    // 是否为移动设备
    isMobile: (state): boolean => state.device === 'mobile',
    
    // 是否显示侧边栏
    showSidebar: (state): boolean => {
      return !state.isMobile || !state.sidebarCollapsed
    },
    
    // 获取活动标签
    activeTab: (state): TabItem | null => {
      return state.tabs.find(tab => tab.path === window.location.pathname) || null
    },
    
    // 获取可关闭的标签
    closableTabs: (state): TabItem[] => {
      return state.tabs.filter(tab => tab.closable)
    },
    
    // 系统标题
    systemTitle: (state): string => {
      return state.config.title
    }
  },

  actions: {
    // 切换侧边栏
    toggleSidebar(withoutAnimation?: boolean): void {
      this.sidebarCollapsed = !this.sidebarCollapsed
      this.sidebarWithoutAnimation = withoutAnimation || false
      
      // 移动设备下自动收起
      if (this.isMobile) {
        this.sidebarCollapsed = true
      }
    },

    // 关闭侧边栏
    closeSidebar(withoutAnimation?: boolean): void {
      this.sidebarCollapsed = true
      this.sidebarWithoutAnimation = withoutAnimation || false
    },

    // 设置设备类型
    setDevice(device: 'desktop' | 'tablet' | 'mobile'): void {
      this.device = device
      
      // 移动设备下自动收起侧边栏
      if (device === 'mobile') {
        this.sidebarCollapsed = true
      }
    },

    // 设置主题
    setTheme(theme: 'light' | 'dark' | 'auto'): void {
      this.theme = theme
      
      // 应用主题到文档
      const html = document.documentElement
      if (theme === 'dark') {
        html.classList.add('dark')
      } else if (theme === 'light') {
        html.classList.remove('dark')
      } else {
        // auto模式根据系统偏好设置
        const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
        if (prefersDark) {
          html.classList.add('dark')
        } else {
          html.classList.remove('dark')
        }
      }
    },

    // 设置主色调
    setPrimaryColor(color: string): void {
      this.primaryColor = color
      
      // 动态设置CSS变量
      document.documentElement.style.setProperty('--el-color-primary', color)
    },

    // 设置语言
    setLanguage(language: string): void {
      this.language = language
    },

    // 设置页面尺寸
    setSize(size: 'default' | 'large' | 'small'): void {
      this.size = size
    },

    // 添加标签页
    addTab(tab: TabItem): void {
      const existingTab = this.tabs.find(t => t.path === tab.path)
      if (existingTab) {
        // 更新已存在的标签
        Object.assign(existingTab, tab)
      } else {
        this.tabs.push(tab)
      }
    },

    // 删除标签页
    removeTab(targetPath: string): void {
      const index = this.tabs.findIndex(tab => tab.path === targetPath)
      if (index > -1) {
        const removedTab = this.tabs.splice(index, 1)[0]
        
        // 从缓存中移除
        this.removeCachedView(removedTab.name)
      }
    },

    // 删除其他标签页
    removeOtherTabs(keepPath: string): void {
      this.tabs = this.tabs.filter(tab => !tab.closable || tab.path === keepPath)
      
      // 清理缓存
      const keepTab = this.tabs.find(tab => tab.path === keepPath)
      if (keepTab) {
        this.cachedViews = [keepTab.name]
      }
    },

    // 删除所有标签页
    removeAllTabs(): void {
      this.tabs = this.tabs.filter(tab => tab.affix)
      this.cachedViews = []
    },

    // 添加缓存视图
    addCachedView(name: string): void {
      if (!this.cachedViews.includes(name)) {
        this.cachedViews.push(name)
      }
    },

    // 移除缓存视图
    removeCachedView(name: string): void {
      const index = this.cachedViews.indexOf(name)
      if (index > -1) {
        this.cachedViews.splice(index, 1)
      }
    },

    // 设置面包屑
    setBreadcrumbs(breadcrumbs: BreadcrumbItem[]): void {
      this.breadcrumbs = breadcrumbs
    },

    // 添加面包屑
    addBreadcrumb(breadcrumb: BreadcrumbItem): void {
      const exists = this.breadcrumbs.some(item => item.path === breadcrumb.path)
      if (!exists) {
        this.breadcrumbs.push(breadcrumb)
      }
    },

    // 设置加载状态
    setLoading(loading: boolean): void {
      this.loading = loading
    },

    // 切换全屏
    toggleFullscreen(): void {
      this.fullscreen = !this.fullscreen
    },

    // 重置应用状态
    resetAppState(): void {
      this.tabs = []
      this.cachedViews = []
      this.breadcrumbs = []
      this.loading = false
      this.fullscreen = false
    },

    // 初始化应用配置
    initAppConfig(): void {
      // 设置主题
      this.setTheme(this.theme)
      
      // 设置主色调
      this.setPrimaryColor(this.primaryColor)
      
      // 监听系统主题变化
      if (this.theme === 'auto') {
        const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
        mediaQuery.addListener(() => {
          this.setTheme('auto')
        })
      }
      
      // 监听窗口大小变化
      const handleResize = () => {
        const width = window.innerWidth
        if (width < 768) {
          this.setDevice('mobile')
        } else if (width < 1024) {
          this.setDevice('tablet')
        } else {
          this.setDevice('desktop')
        }
      }
      
      handleResize()
      window.addEventListener('resize', handleResize)
    },

    // 更新系统配置
    updateConfig(config: Partial<SystemConfig>): void {
      this.config = { ...this.config, ...config }
    }
  },

  // 持久化配置
  persist: {
    key: 'kexio-app-store',
    // ✅ 统一使用 localStorage，通过启动时检查和登出时清除来实现"记住我"功能
    storage: localStorage,
    paths: [
      'theme',
      'primaryColor', 
      'layout',
      'fixedHeader',
      'fixedSidebar',
      'showBreadcrumb',
      'showTabs',
      'showFooter',
      'language',
      'size'
    ]
  }
})
